package io.renren.controller;

import io.renren.entity.FileManagementEntity;
import io.renren.entity.SysUserEntity;
import io.renren.service.FileManagementService;
import io.renren.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 文件管理
 * 
 * @author zhangheng
 * @email zh_123shmily@163.com
 * @date 2017-07-11 17:19:10
 */
@RestController
@RequestMapping("filemanagement")
public class FileManagementController extends  AbstractController{
	@Autowired
	private FileManagementService fileManagementService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("filemanagement:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        QueryAuthority query = new QueryAuthority(params);

		List<FileManagementEntity> fileManagementList = fileManagementService.queryList(query);
		int total = fileManagementService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(fileManagementList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("filemanagement:info")
	public R info(@PathVariable("id") Integer id){
		FileManagementEntity fileManagement = fileManagementService.queryObject(id);
		
		return R.ok().put("fileManagement", fileManagement);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("filemanagement:save")
	public R save(@RequestBody FileManagementEntity fileManagement){
		fileManagementService.save(fileManagement);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("filemanagement:update")
	public R update(@RequestBody FileManagementEntity fileManagement){
		fileManagementService.update(fileManagement);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("filemanagement:delete")
	public R delete(@RequestBody Integer[] ids){
		for (Integer id : ids) {
			FileManagementEntity fileManagement = fileManagementService.queryObject(id);
			String url = fileManagement.getUrl();
			new File(url).delete();
		}
		fileManagementService.deleteBatch(ids);
		
		return R.ok();
	}

	/**
	 * 上传文件
	 */
	@RequestMapping(value ="/upload", method = RequestMethod.POST,headers={"Content-Type=multipart/form-data"})
	@RequiresPermissions("filemanagement:update")
	public R upload(@RequestParam("file") MultipartFile file) {
		String filePath ="";
		;		// 判断文件是否为空
		if (!file.isEmpty()) {
			if(file.getSize()>10240000)
			{
				throw new RRException("上传失败：文件大小不能超过10M");
			}
			try {
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				;
				// 文件保存路径
				filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\"+getUser().getUsername()+"_"
						+ DateUtils.format(new Date(),"yyyyMMddHHmmss")+postfix;
				File saveDir = new File(filePath);

				//判断目标文件所在的目录是否存在
				if(!saveDir.getParentFile().exists()) {
					//如果目标文件所在的目录不存在，则创建父目录
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			throw new RRException("上传失败:请添加上传文件！");
		}

		//保存文件信息
		FileManagementEntity pojo = new FileManagementEntity();
		pojo.setUrl(filePath);
		pojo.setUploadTime(new Date());
		pojo.setFileName(file.getOriginalFilename());
		SysUserEntity entity= (SysUserEntity) ShiroUtils.getSubject().getSession().getAttribute("user");
		pojo.setCdate(new Date());
		pojo.setCusername(entity.getUsername());
		pojo.setCompanyId(entity.getCompanyId());
		pojo.setDeptId(entity.getDeptNo());
		fileManagementService.save(pojo);

		return R.ok().put("url", filePath).put("fileId",pojo.getId());
	}



	/**
	 * 下载
	 */
	@RequestMapping("/download")
	@RequiresPermissions("filemanagement:update")
	public R download() {
		try {
			String id = request.getParameter("id");
			FileManagementEntity pojo = fileManagementService.queryObject(Integer.valueOf(id));
			String url = pojo.getUrl();
			//提取后缀
			String postfix = url.substring(url.lastIndexOf("."));
			//设置文件MIME类型
			response.setContentType(request.getSession().getServletContext().getMimeType(url));
			//设置Content-Disposition
			response.setHeader("Content-Disposition", "attachment;filename=" + DateUtils.format(new Date(),"yyyyMMddHHmmss")+postfix);
			//读取目标文件，通过response将目标文件写到客户端
			File file = new File(url);
			if (!file.exists()){
				throw new RRException("系统找不到指定的文件。");
			}
			//读取文件
			InputStream in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len=0;
			while((len = in.read(buf)) != -1 ){
				out.write(buf,0,len);
			}
			in.close();
			out.flush();
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok();
	}
	
}
